<template>
  <div class="container">
    <h3>编辑书籍</h3>
    <el-form :model="book" label-width="120px">
      <el-form-item label="ID">
        <el-input v-model="book.id" disabled></el-input>
      </el-form-item>
      <el-form-item label="书名">
        <el-input v-model="book.name"></el-input>
      </el-form-item>
      <el-form-item label="类型">
        <el-input v-model="book.type"></el-input>
      </el-form-item>
      <el-form-item label="描述">
        <el-input v-model="book.information"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm">提交</el-button>
        <el-button @click="cancel">取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import axios from 'axios'
import { ElMessage } from 'element-plus';

const route = useRoute()
const router = useRouter()
const book = ref({ id: null, name: '', type: '' ,information: '' })

// 获取书籍详情
const fetchBook = async () => {
  try {
    const id = route.query.id
    const res = await axios.get(`http://localhost:8080/book/${id}`)
    book.value = res.data
  } catch (error) {
    console.error('获取书籍失败:', error)
    ElMessage.error('获取书籍信息失败')
  }
}

// 提交表单
const submitForm = async () => {
  try {
    await axios.put('http://localhost:8080/', book.value)
    ElMessage.success('更新成功')
    router.push({ name: 'books' })
  } catch (error) {
    console.error('更新失败:', error)
    ElMessage.error('更新失败')
  }
}

// 取消编辑
const cancel = () => {
  router.go(-1)
}

onMounted(fetchBook)
</script>